#all import
from flask import Flask, request, session, g,redirect, url_for,\
    abort, render_template, flash
from db import *

#configuration
DEBUG = True
SECRET_KEY = 'development key'

#create app

app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/')
def home_page():
    qsession = get_session()
    entries=qsession.query(blogtable.blogid, blogtable.userid, blogtable.created_date, blogtable.title, blogtable.text, usertable.name).filter(blogtable.userid ==  usertable.userid).all()
    alltype = qsession.query(typetable).all()
    return render_template('show_entries.html', entries=entries,  alltype=alltype)

@app.route('/type/<int:typeid>', methods=['GET'])
def show_type_blog(typeid):
    qsession = get_session()
    entries=qsession.query(blogtable.blogid, blogtable.userid, blogtable.created_date, blogtable.title, blogtable.text, usertable.name).filter(blogtable.userid ==  usertable.userid, blogtable.typeid == typeid).all()
    alltype = qsession.query(typetable).all()
    return render_template('show_entries.html', entries=entries,  alltype=alltype)

@app.route('/myblog')
def myblog():
    qsession = get_session()
    entries=qsession.query(blogtable.blogid, blogtable.userid, blogtable.created_date, blogtable.title, blogtable.text, usertable.name).filter(blogtable.userid ==  usertable.userid, blogtable.userid==session['cur_user_id']).all()
    alltype = qsession.query(typetable).all()
    return render_template('show_entries.html', entries=entries,  alltype=alltype)


@app.route('/aboutme')
def about_me():
    return render_template('about.html')

@app.route('/search', methods=['GET', 'POST'])
def search():
    keyword = request.form['search']
    str_list = ['%',keyword,'%']
    str_keyword = ''.join(str_list)
    qsession = get_session()
    entries=qsession.query(blogtable.blogid, blogtable.userid, blogtable.created_date, blogtable.title, blogtable.text, usertable.name).filter((blogtable.userid ==  usertable.userid), (blogtable.title.like(str_keyword))).all()
    alltype = qsession.query(typetable).all()
    #return render_template('test.html', typeid=keyword)
    return render_template('show_entries.html', entries=entries,  alltype=alltype)

@app.route('/comment/<int:blogid>', methods=['GET', 'POST'])
def comment(blogid):
    com = commenttable(
        blogid = blogid,
        comment_by_id = session['cur_user_id'],
        comment_text = request.form['text']
    )
    qsession = get_session()
    qsession.add(com)
    qsession.commit()
    return redirect(url_for('show_blog', blogid=blogid))

@app.route('/del_blog/<int:blogid>')
def del_blog(blogid):
    qsession = get_session()
    blog = qsession.query(blogtable).filter_by(blogid=blogid).first()
    qsession.delete(blog)
    qsession.commit()
    return redirect(url_for('home_page'))


@app.route('/edit_blog/<int:blogid>', methods=['GET', 'POST'])
def edit_blog(blogid):
    qsession = get_session()
    blog = qsession.query(blogtable).filter_by(blogid=blogid).first()
    if request.method == 'POST':
        blog.title = request.form['title']
        blog.text = request.form['text']
        qsession.commit()
        return redirect(url_for('home_page'))
    return render_template('blog_edit.html', blog=blog)

@app.route('/<int:blogid>', methods=['GET'])
def show_blog(blogid):
    qsession = get_session()
    blog = qsession.query(blogtable.blogid, blogtable.title, blogtable.created_date,  blogtable.text, usertable.name).filter(blogtable.blogid==blogid, usertable.userid==blogtable.userid).first()
    comments = qsession.query(commenttable.comment_text, usertable.name).filter(blogid==blogid, commenttable.comment_by_id==usertable.userid).all()
    alltype = qsession.query(typetable).all()
    return render_template('show_blog.html', blog=blog, comments=comments, alltype=alltype)



def add_blog(userid, title, text, typeid):
    blog = blogtable(
        userid = userid,
        title = title,
        text = text,
        typeid = typeid
    )
    qsession = get_session()
    qsession.add(blog)
    qsession.commit()

@app.route('/add_type', methods=['GET', 'POST'])
def add_type():
    if(request.method == 'POST'):
        typename = request.form['typename']
        qsession = get_session()
        type_instance = typetable(
                typename = typename,
            )
        qsession.add(type_instance)
        qsession.commit()

        return redirect(url_for('home_page'))
    return render_template('add_type.html')

@app.route('/publish', methods=['GET', 'POST'])
def publish():
    if request.method == 'POST':
        userid = session['cur_user_id']
        title = request.form['title']
        text = request.form['text']
        typeid = request.form['type']

        add_blog(userid, title, text, typeid)
        qsession = get_session()
        type_instance = qsession.query(typetable).filter_by(typeid=typeid).first()
        type_instance.typecount = type_instance.typecount+1
        qsession.commit()
        temp = type_instance.typecount
        #return render_template('test.html', typeid=temp)
        return redirect(url_for('home_page'))

@app.route('/new_blog', methods=['GET'])
def new_blog():
    qsession = get_session();
    alltype = qsession.query(typetable).all()
    #return render_template('test.html', typeid=3)
    return render_template('blog_edit.html', alltype=alltype)

def add_user(username, password):
    user = usertable(
        name = username,
        passwd = password
    )
    qsession = get_session()
    qsession.add(user)
    qsession.commit()

@app.route('/register', methods=['GET', 'POST'])
def register():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        add_user(username, password)
        flash('you were register')
        return redirect(url_for('home_page'))
    return render_template('register.html', error=error)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        qsession = get_session()
        username = request.form['username']
        query = qsession.query(usertable).filter_by(name=username).first()
        if(query != None):
            if query.passwd != request.form['password']:
                flash('error password, please retry')
                return redirect(url_for('login'))
            else:
                session['logged_in'] = True
                session['cur_username'] = username
                session['cur_user_id'] = query.userid
                flash('you were logged in')
                return redirect(url_for('home_page'))
        else:
            error = 'no some user'
    return render_template('login.html', error=error)

@app.route('/logout',methods=['GET'])
def logout():
    session.pop('logged_in', None)
    session['cur_user_id'] = None
    flash('you were logged out')
    return redirect(url_for('home_page'))

if __name__=='__main__':
    app.run(host='0.0.0.0')